<?php

    class BrandController extends Zend_Controller_Action
    {

        public function init()
        {
            
        }

        public function indexAction()
        {
            @session_start();
            
            if(isset($_SESSION['connect']))
                $connect = $_SESSION['connect'];
            else
                $connect = 'off';
            
            
            $this->view->connect = $connect;
            
            $whereCond = "status = '1'";

            $brandName = $this->_getParam('brand_name');

            if ($this->_getParam('brand_name'))
                $whereCond = "brand_status = '1' AND b.brand_name = '$brandName' ";
            else
                $this->_redirect('brand/all');

            $model = new Application_Model_Common();
            $records = $model->getAllRecordFromLeftJoin(array("b" => "rkn_brand"), array("p" => "rkn_product"), "p.brand_id=b.brand_id", $whereCond, "rkn_prod_id");


            $records = $model->getAdapter()->select()->from(array("b" => "rkn_brand"))
                    ->joinLeft(array("p" => "rkn_product"), "p.brand_id=b.brand_id")
                    ->join(array("c" => "rkn_category"), "p.cat_id=c.cat_id")
                    ->joinLeft(array("sub" => "rkn_sub_category"), "sub.scat_id = p.sub_cat_id", array("scat_id", "cat_name as sub_cat_name"))
                    ->joinLeft(array("sc" => "rkn_sub_child_category"), "sc.schild_id = p.schild_id")
                    ->where("p.status = '1' and  $whereCond ")
                    ->order('rkn_prod_id desc')
            ;

//            $records = $model->getAdapter()->select()->from(array("b" => "rkn_brand"))
//                    ->joinLeft(array("p" => "rkn_product"), "p.brand_id=b.brand_id")
//                    ->join(array("c" => RKN_CATEGORY), "c.cat_id = p.cat_id")
//                    ->joinLeft(array("s" => "rkn_sub_category"), "s.scat_id = p.sub_cat_id")
//                    ->where($whereCond)
//            ;

            //prd($records->__toString());
            $records = $records->query()->fetchAll();

            //prd($records);
            if (!empty($records))
                $this->view->assign($records[0]);

            $brand_video_arr = explode("|||", $records[0]["brand_video"]);
            $this->view->brand_video_arr = $brand_video_arr;

            $social_media_decode = json_decode($records[0]["brand_social_connection"]);
            $this->view->social_media_object = $social_media_decode;
            $this->view->alldata = $records;

            //get counts of trends with same brand id
            $trendrecords = $model->getAllRecordFromInnerJoin(RKN_PRODUCT, RKN_BRAND, RKN_BRAND . ".brand_id = " . RKN_PRODUCT . ".brand_id ", " is_trend='1' and " . RKN_PRODUCT . ".brand_id = '" . $records[0]['brand_id'] . "' ");
            $this->view->trenddata = $trendrecords;
        }

        public function allAction()
        {
            $model = new Application_Model_Common();
            $alldata = $model->getAllRecordDetail(RKN_BRAND);
            $type = $this->_getParam('type');
            //$this->view->alldata = $alldata;
            if ($this->getRequest()->isPost())
            {
                $search_text = $this->getRequest()->getPost('text');
                $where = " and  locate('" . strtolower($search_text) . "',lower(search_words)) > 0 ";
            }

            //trend count
//            $trendSubQuery = new Zend_Db_Expr('(select count(*) from ' . RKN_PRODUCT . ' inner join ' . RKN_BRAND . ' on ' . RKN_BRAND . '.brand_id = ' . RKN_PRODUCT . '.brand_id where ' . RKN_PRODUCT . '.status = "1" and ' . RKN_BRAND . '.brand_status = "1" and ' . RKN_PRODUCT . '.is_trend = "1" '.$where.' ) as _total  ');
//            $trenddata = $model->getAdapter()->select()->from(array('b' => RKN_BRAND), array('brand_id', 'brand_name', 'brand_keywords', 'brand_photo', 'brand_status', $trendSubQuery))
//                    ->join(array('p' => RKN_PRODUCT), 'p.brand_id = b.brand_id')
//                    ->where(" is_trend = '1' and status = '1' and brand_status = '1' $where ")
//                    ->group("b.brand_id")
//            ;
//
//            $trenddata = $trenddata->query()->fetchAll();
            //prd($trenddata);
//            $this->view->trenddata = $trenddata;
//            $this->view->trendTotal = (int) $trenddata[0]['_total'];
            //brand count
            $productSubQuery = new Zend_Db_Expr('(select count(*) from ' . RKN_PRODUCT . ' inner join ' . RKN_BRAND . ' on ' . RKN_BRAND . '.brand_id = ' . RKN_PRODUCT . '.brand_id where ' . RKN_PRODUCT . '.status = "1" and ' . RKN_BRAND . '.brand_status = "1" ' . $where . ' ) as _total  ');
            $productdata = $model->getAdapter()->select()->from(array('b' => RKN_BRAND), array('brand_id', 'brand_name', 'brand_keywords', 'brand_photo', 'brand_status', $productSubQuery))
                    ->join(array('p' => RKN_PRODUCT), 'p.brand_id = b.brand_id ')
                    ->where(" p.status = '1' and b.brand_status = '1' $where ")
                    ->group("b.brand_id")
            ;

            //prd($productdata->__toString());
            $productdata = $productdata->query()->fetchAll();
            $this->view->productdata = $productdata;
            $this->view->productTotal = empty($productdata[0]['_total']) ? 0 : $productdata[0]['_total'];
            $this->view->alldata = ($type == 'product' || empty($type) ? $productdata : $socialdata);
            $this->view->params = $this->getRequest()->getParams();
            $this->view->search_text = $search_text;
            //prd($this->getRequest()->getParams());
            //prd($trenddata);
        }

        public function getInstagramMedia($instaTag = "raeken")
        {

            $tag = $instaTag;
            $client_id = INSTAGRAM_CLIENT_ID;
            $url = 'https://api.instagram.com/v1/tags/' . $tag . '/media/recent?client_id=' . $client_id;

            $inst_stream = callInstagram($url);
            $results = json_decode($inst_stream, true);
            //prd($results);
            $image_link = $results['data'][0]['images']['low_resolution']['url'];
            $created_time = $results['data'][0]['created_time'];
            $likes = $results['data'][0]['likes']['count'];

            $array = array(
                "image_link" => $image_link,
                "created_time" => getTimeAgo($created_time),
                "likes" => $likes
            );

            return $array;
        }

        public function getFacebookStatusUpdates($pageid, $postCount = "2", $startFrom = "0")
        {
            $appid = FACEBOOK_APP_ID;
            $secret = FACEBOOK_SECRET_ID;

            $feed = @file_get_contents('https://graph.facebook.com/' . $pageid . '/feed?access_token=' . $appid . '|' . $secret);
            $jsonData = json_decode($feed);
            $result = @(array) $jsonData->data;
//            prd($result);

            $new_array = array();
            $i = $startFrom;
//            foreach ($result as $key => $value)
//            {
//                if (isset($value->message))
//                {
//                    $new_array[] = array(
//                        "message" => $value->message,
//                        "updated_time" => $value->updated_time,
//                        "likes" => count($value->likes->data),
//                        "comments" => count($value->comments->data),
//                    );
//                    $i++;
//                    if ($i == $postCount)
//                        break;
//                }
//            }

            $newPostCount = "0";
            for ($i = $startFrom; $i <= $postCount; $i++)
            {
                $value = $result[$i];
                if (isset($value->message))
                {
                    $new_array[] = array(
                        "message" => $value->message,
                        "updated_time" => $value->updated_time,
                        "likes" => count($value->likes->data),
                        "comments" => count($value->comments->data),
                    );
                    $newPostCount++;
                    if ($newPostCount == $postCount)
                        break;;
                }
            }

            return $new_array;
        }

        public function getTwitterUpdates($twitter_id, $tweet_count = "1")
        {
            require_once APPLICATION_PATH . "/../assets/twitteroauth/twitteroauth.php";

            $twitteruser = $twitter_id;
            $notweets = $tweet_count;
            $consumerkey = TWITTER_APP_ID;
            $consumersecret = TWITTER_SECRET_ID;

            $connection = new TwitterOAuth($consumerkey, $consumersecret);
            $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets);
//            prd($tweets);

            $new_array = array();
            foreach ($tweets as $key => $value)
            {
                $new_array[] = array("message" => $value->text, "created_time" => $value->created_at);
            }

            return $new_array;
        }

        public function productsAction()
        {
            $this->_helper->layout->disableLayout();

//            if ($this->getParam("product_id"))
            if ($this->getParam("product_id"))
            {
                $product_id = $this->_getParam("product_id");
                $product_id = getEncryptedString($this->_getParam("product_id"), "decode");
                $model = new Application_Model_Common();
                $whereCond = "status = '1' AND rkn_prod_id = $product_id";
                $records = $model->getAllRecordFromInnerJoin(array("p" => "rkn_product"), array("b" => "rkn_brand"), "p.brand_id=b.brand_id", $whereCond);

                $similarWhereCond = "status = '1' AND rkn_prod_id != $product_id";
                $similarRecords = $model->getAllRecordFromInnerJoin(array("p" => "rkn_product"), array("b" => "rkn_brand"), "p.brand_id=b.brand_id", $similarWhereCond, "p.rkn_prod_id DESC", "8");

                $this->view->alldata = $records[0];
                $this->view->similarRecords = $similarRecords;

                $this->recordsVisitedProduct($product_id);
            }
        }

        public function recordsVisitedProduct($product_id)
        {
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (!empty($y))
            {
                $model = new Application_Model_Common();
                $user_id = $x->read()->rkn_uid;
                $product_record = $model->getdata(RKN_PRODUCT, "rkn_prod_id=$product_id");
                $brand_id = $product_record["brand_id"];

                $is_exist = $model->is_exists(RKN_VISIT_PROD, "product_id = $product_id AND brand_id = $brand_id AND user_id = $user_id");
                if (empty($is_exist))
                {
//                insert
                    $data_array = array(
                        "user_id" => $user_id,
                        "product_id" => $product_id,
                        "brand_id" => $brand_id,
                        "ip" => $_SERVER["REMOTE_ADDR"],
                        "no_visit" => "1"
                    );
                    $model->insertRecordData($data_array, RKN_VISIT_PROD);
                }
                else
                {
//            update    
                    $visit_id = $is_exist["visit_id"];
                    $sql = "UPDATE " . RKN_VISIT_PROD . " SET `ip` = '" . $_SERVER["REMOTE_ADDR"] . "',  no_visit = no_visit+1 WHERE visit_id = $visit_id";
                    $model->getAdapter()->query($sql);
                }
            }
        }

        public function getinstagramfromajaxAction()
        {
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                $insta_id = $arr["insta_id"];
                $insta_count = $arr["insta_count"];

                $instagram_array = getInstagramMedia($insta_id, $insta_count + 1);
                $instaImageLink = $instagram_array[$insta_count]["image_link"];
                $instaImageTimeAgo = $instagram_array[$insta_count]["created_time"];
                $instaImageLikes = number_format($instagram_array[$insta_count]["likes"]);


                $str = '<div class="top">
                            <img src="' . IMAGES_PATH . '"/insta-circle.png"" alt="insta-circle"/>
                            <p>' . $instaImageTimeAgo . '</p>
                        </div>
                        <img src="' . $instaImageLink . '" alt="Instagram" class="friend-img"/>
                        <div class="bottom" style="margin-top: -40px;">
                            <p>' . $instaImageLikes . ' Likes</p>
                        </div>';

                echo $str;
            }
            die;
        }

    }